package com.xcj.springai.chatMemory;


/**
 * 读取文件，并存入向量库
 */


import org.apache.commons.io.FilenameUtils;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.reader.JsonReader;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.reader.jsoup.JsoupDocumentReader;
import org.springframework.ai.reader.jsoup.config.JsoupDocumentReaderConfig;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.ai.reader.pdf.ParagraphPdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.List;

@Component
public class CompositeDocumentReader implements InitializingBean {

    @Value("${g2s.xiaogong.knowledgePath}")
    private String knowledgePath;
    private final VectorStore vectorStore;

    public CompositeDocumentReader(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    /**
     * 读文件的版本
     * @param resource
     * @throws Exception
     */
//    private void loadDocument(Resource resource) throws Exception {
//    String filename = resource.getFilename();
//    if (filename == null) return;
//    String extension = FilenameUtils.getExtension(filename);
//    DocumentReader reader = null;
//    if ("md".equalsIgnoreCase(extension)|| "txt".equalsIgnoreCase(extension)) {
//        reader = new MarkdownDocumentReader(resource, MarkdownDocumentReaderConfig.defaultConfig());
//    } else if ("pdf".equalsIgnoreCase(extension)) {
//        reader = new ParagraphPdfDocumentReader(resource, PdfDocumentReaderConfig.defaultConfig());
//    }
//    if (reader != null) {
//        List<Document> documents = reader.get();
//        if (!documents.isEmpty()) {
//            vectorStore.add(documents);
//        }
//    }
//}
//
//    @Override
//    public void afterPropertiesSet() throws Exception {
//        Resource resource;
//        if (knowledgePath.startsWith("classpath:")) {
//            // 处理 classpath 下的单个文件
//            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//            resource = resolver.getResource(knowledgePath);
//            if (!resource.exists()) {
//                throw new IllegalArgumentException("资源文件不存在: " + knowledgePath);
//            }
//            System.out.println("加载 classpath 文件：" + resource.getFilename());
//            loadDocument(resource);
//        } else {
//            // 文件系统路径
//            File file = new File(knowledgePath);
//            if (!file.exists()) {
//                throw new IllegalArgumentException("文件不存在: " + knowledgePath);
//            }
//            System.out.println("加载文件系统文件：" + file.getName());
//            loadDocument(new FileSystemResource(file));
//        }
//    }


    /**
     *读文件夹的版本
     */
    private void loadDocument(File file) {
        String extension = FilenameUtils.getExtension(file.getName()).toLowerCase();
        FileSystemResource resource = new FileSystemResource(file);
        DocumentReader reader = switch (extension) {
            case "json" -> new JsonReader(resource);
            case "txt" -> new TextReader(resource);
            case "html" -> new JsoupDocumentReader(resource, JsoupDocumentReaderConfig.defaultConfig());
            case "md" -> new MarkdownDocumentReader(resource, MarkdownDocumentReaderConfig.defaultConfig());
            case "pdf" -> new ParagraphPdfDocumentReader(resource, PdfDocumentReaderConfig.defaultConfig());
            case "doc", "docx", "ppt", "pptx" -> new TikaDocumentReader(resource);
            default -> null;
        };
        if (reader != null) {
            List<Document> documents = reader.read();
            if (!documents.isEmpty()) {
                vectorStore.add(documents);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String[] extensions = { "json", "txt", "html", "md", "pdf", "doc", "docx", "ppt", "pptx" };

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String pattern = "classpath:" + knowledgePath + "/**/*.*"; // 加通配符

        Resource[] resources = resolver.getResources(pattern);

        for (Resource resource : resources) {
            if (resource.isFile()) {
                File file = resource.getFile(); // 仅当资源是可转换为 File 的情况使用
                String ext = FilenameUtils.getExtension(file.getName()).toLowerCase();
                if (List.of(extensions).contains(ext)) {
                    loadDocument(file);
                }
            }
        }
    }


  }
